package com.wxl.xueyuan.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wxl.xueyuan.MyApp;
import com.wxl.xueyuan.R;
import com.wxl.xueyuan.adapter.ArticleAdapter;
import com.wxl.xueyuan.api.Api;
import com.wxl.xueyuan.api.ApiConfig;
import com.wxl.xueyuan.api.MCallback;
import com.wxl.xueyuan.entity.ArticleEntity;
import com.wxl.xueyuan.entity.ArticleListResponse;
import com.wxl.xueyuan.util.ActivityCollectorUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lombok.SneakyThrows;

public class DownloadActivity extends BaseActivity {

    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    private int pageNum = 1;
    private ArticleAdapter articleAdapter;
    private List<ArticleEntity> datas = new ArrayList<>();
    private LinearLayoutManager linearLayoutManager;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    articleAdapter.setDatas(datas);
                    articleAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected int initLayout() {
        return R.layout.activity_download;
    }

    @Override
    protected void initView() {
        recyclerView = findViewById(R.id.recyclerView);
        refreshLayout = findViewById(R.id.refreshLayout);
        ActivityCollectorUtil.addActivity(DownloadActivity.this);
    }

    @Override
    protected void initData() {
        ImageButton back = findViewById(R.id.back);
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        articleAdapter = new ArticleAdapter(this);
        recyclerView.setAdapter(articleAdapter);
        articleAdapter.setOnItemClickListener(new ArticleAdapter.OnItemClickListener() {
            @SneakyThrows
            @Override
            public void onItemClick(Serializable obj) {
                ArticleEntity aEntity = (ArticleEntity) obj;
                Integer rId = aEntity.getRecordId();
                Api.otherConfig("/" + rId, null).getRequest(DownloadActivity.this, new MCallback() {
                    @SneakyThrows
                    @Override
                    public void onSuccess(String res) {
                        ObjectMapper mapper = new ObjectMapper();
                        ArticleEntity articleEntity = mapper.readValue(res, ArticleEntity.class);
                        //更改图片url
                        String str = "<img.*src=.*width.*>";
                        List<String> photos = articleEntity.getPhotos();
                        String rawHtml = articleEntity.getRawHtml();
                        for (int i = 0; i < photos.size(); i++) {
                            StringBuffer sb = new StringBuffer();
                            sb.append("<img src=\"").append(photos.get(i)).append("\"><br /><br />");
                            rawHtml = rawHtml.replaceFirst(str, sb.toString());
                        }
                        articleEntity.setRawHtml(rawHtml);
                        //发送文章和浏览记录
                        new Thread(new Runnable() {
                            @SneakyThrows
                            @Override
                            public void run() {
                                HashMap<String, Object> params = new HashMap<>();
                                params.put("recordId", articleEntity.getRecordId());
                                params.put("title", articleEntity.getTitle());
                                params.put("publishedAt", articleEntity.getPublishedAt());
                                params.put("ID", MyApp.getmData("ID"));
                                Api.config("/article/addVisitArticle", params).getRequest(DownloadActivity.this, new MCallback() {
                                    @Override
                                    public void onSuccess(final String res) {
                                        String thumb_up_state = "0";
                                        String collection_state = "0";
                                        switch (res) {
                                            case "01" :
                                                collection_state = "1";
                                                break;
                                            case "10" :
                                                thumb_up_state = "1";
                                                break;
                                            case "11" :
                                                collection_state = "1";
                                                thumb_up_state = "1";
                                                break;
                                        }
                                        //跳转详情页面
                                        Bundle bundle=new Bundle();
                                        bundle.putString("record_id", String.valueOf(articleEntity.getRecordId()));
                                        bundle.putString("title", articleEntity.getTitle());
                                        bundle.putString("published_at", articleEntity.getPublishedAt());
                                        bundle.putString("raw_html", articleEntity.getRawHtml());
                                        bundle.putString("thumb_up_state", thumb_up_state);
                                        bundle.putString("collection_state", collection_state);
                                        Intent in = new Intent(DownloadActivity.this, DetailActivity.class);
                                        in.putExtras(bundle);
                                        startActivity(in);
                                    }
                                    @Override
                                    public void onFailure(Exception e) {

                                    }
                                });
                            }
                        }).start();
                    }

                    @Override
                    public void onFailure(Exception e) {

                    }
                });

            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                getDownloadList(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                pageNum++;
                getDownloadList(false);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownloadActivity.super.onBackPressed();
            }
        });
        getDownloadList(true);
    }

    private void getDownloadList(final boolean isRefresh) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("ID", MyApp.getmData("ID"));
        params.put("page", pageNum);
        params.put("size", ApiConfig.PAGE_SIZE);
        Api.config("/article/queryDownloadPS", params).getRequest(this, new MCallback() {
            @SneakyThrows
            @Override
            public void onSuccess(final String res) {
                if (isRefresh) {
                    refreshLayout.finishRefresh(true);
                } else {
                    refreshLayout.finishLoadMore(true);
                }
                ObjectMapper mapper = new ObjectMapper();
                ArticleListResponse response = mapper.readValue(res, ArticleListResponse.class);
                if (response != null) {
                    List<ArticleEntity> list = response.getItems();
                    if (list != null && list.size() > 0) {
                        if (isRefresh) {
                            datas = list;
                        } else {
                            datas.addAll(list);
                        }
                        mHandler.sendEmptyMessage(0);
                    } else {
                        if (isRefresh) {
                            showToastSync("暂时无数据");
                        } else {
                            showToastSync("没有更多数据");
                        }
                    }
                }
            }

            @Override
            public void onFailure(Exception e) {
                if (isRefresh) {
                    refreshLayout.finishRefresh(true);
                } else {
                    refreshLayout.finishLoadMore(true);
                }
            }
        });
    }
}